
#include "taskrequest.h"
#include "log.h"
#include "components/attachment.h"
#include <boost/bind.hpp>

namespace Wishmaster
{
	TaskRequest::TaskRequest(RequestType type, const Wishmaster2::Network::Url& link, const QString& msg,
			Wishmaster2::Network::RequestManager* requestManager) : Task(msg),
		m_type(type),
		m_link(link),
		m_requestManager(requestManager)
	{

	}

	TaskRequest::~TaskRequest()
	{
	}

	TaskRequest::RequestType TaskRequest::requestType() const
	{
		return m_type;
	}

	Wishmaster2::Network::Url TaskRequest::link() const
	{
		return m_link;
	}

	void TaskRequest::start()
	{
		if(!m_requestManager)
			return;

		m_request = m_requestManager->createRequest(link());
		m_request->connectSignalFinished(boost::bind(&TaskRequest::requestDone, this, _1));
		m_requestManager->enqueueRequest(m_request);
		Task::start();
	}

	void TaskRequest::cancel()
	{
		//m_request->cancel();
		Task::cancel();
	}


	Wishmaster2::Network::RequestPtr TaskRequest::request() const
	{
		return m_request;
	}

	void TaskRequest::slot_progress(int done, int total)
	{
		//log(llDebug, "pr: %d/%d", done, total);
		setPercentage((double)done / total * 100.);
		emit progress(id(), done, total);
	}

	void TaskRequest::requestDone(int requestId)
	{
		onRequestDone();
		QByteArray arr(request()->content()->data(), request()->content()->size());
		emit result(this, arr, QString::fromStdString(request()->contentType()));
		emit done(id());
	}

	void TaskRequest::onRequestDone()
	{

	}
}

